package org.linlinjava.litemall.admin.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.tuna.client.api.MessageProcessException;
import com.alibaba.tuna.client.websocket.TunaWebSocketClient;
import com.alibaba.tuna.client.websocket.WebSocketMessage;
import com.alibaba.tuna.client.websocket.WebSocketMessageHandler;
import com.alibaba.tuna.client.websocket.WebSocketMessageType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.linlinjava.litemall.admin.alibaba.vo.AlibabaMessageGoodsSkuVo;
import org.linlinjava.litemall.admin.service.AdminGoodsService;
import org.linlinjava.litemall.admin.service.AdminOrderService;
import org.linlinjava.litemall.admin.service.AlibabaService;
import org.linlinjava.litemall.core.config.GlobalConfig;
import org.linlinjava.litemall.admin.service.AlibabaGoodsChangeService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;


@Component
public class AlibabaMessageController  implements ApplicationRunner {
    private final Log logger = LogFactory.getLog(AlibabaMessageController.class);

    @Autowired
    private AlibabaGoodsChangeService alibabaGoodsChangeService;
    @Autowired
    private AlibabaService alibabaService;
    @Autowired
    private AdminGoodsService adminGoodsService;
    @Autowired
    private AdminOrderService adminOrderService;
    @Override
    public void run(ApplicationArguments args) throws Exception {


        /*
         * 开放平台1688环境
         */
        String url = "ws://message.1688.com/websocket";
        /**
         * 您的 AppKey
         */
        String appKey = GlobalConfig.AlibabaAppId;
        /**
         * 您的应用秘钥
         */
        String secret = GlobalConfig.AlibabaAppSecret;
        /**
         * 您客户端设置的接收线程池大小 默认为虚拟机内核数*40 用户可以自行修改
         */
        int threadNum = 100;

        /**
         * 1. 创建 Client，如果不传入threadNum参数的话，client将使用默认线程数
         */
        TunaWebSocketClient client = new TunaWebSocketClient(appKey, secret, url);
        /**
         * 2. 创建 消息处理 Handler
         */
        WebSocketMessageHandler tunaMessageHandler = new WebSocketMessageHandler() {
            /**
             * 消费消息。
             * 如果抛异常或返回 false，表明消费失败，如未达重试次数上限，开放平台将会择机重发消息
             */
            public boolean onMessage(WebSocketMessage message) throws MessageProcessException {
                boolean success = true;
                /**
                 * 服务端推送的消息分为2种，
                 * 业务数据：SERVER_PUSH
                 * 系统消息：SYSTEM，如 appKey 与 secret 不匹配等，一般可忽略
                 */
                if(WebSocketMessageType.SERVER_PUSH.name().equals(message.getType())) {
                    try {
                        /**
                         * json串
                         */

                        Object obj=JSON.parse( message.getContent());


                        JSONObject jsonObject = JSONObject.parseObject(message.getContent());
                        if(jsonObject.get("type").toString().equals(GlobalConfig.messageSkuType)){
                            //接收库存变更信息
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            JSONArray arr = JSON.parseArray(jsonObject.get("OfferInventoryChangeList").toString());
                            for (int i =0 ;i<arr.size();i++){
                                AlibabaMessageGoodsSkuVo Vo = new AlibabaMessageGoodsSkuVo();
                                JSONObject jsonli = JSONObject.parseObject(arr.get(i).toString());
                               // Vo.setBizTime(jsonli.get("bizTime").toString());
                                Vo.setOfferId(jsonli.get("offerId").toString());
                                //Vo.setOfferOnSale(jsonli.get("offerOnSale").toString());
                               // Vo.setQuantity(jsonli.get("quantity").toString());
                                Vo.setSkuOnSale(jsonli.get("skuOnSale").toString());
                                Vo.setSkuId(jsonli.get("skuId").toString());
                                alibabaService.skuMessageChange(Vo);
                            }
                        }else  if(jsonObject.get("type").toString().equals(GlobalConfig.SENDGOODS)){
                            logger.info("获取到订单发货订阅消息");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  orderId =  jsonObject.get("orderId").toString();
                            logger.info(orderId);
                            /**
                             *
                             * 根据orderId获取物流单号和物流公司信息 同步到order表
                             * */
                            alibabaService.getLogisticsInfos(orderId);

                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.part_sendGoods)){
                            logger.info("商品部分发货");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  orderId =  jsonObject.get("orderId").toString();
                            logger.info(orderId);
                            /**
                             *
                             * 根据orderId获取物流单号和物流公司信息 同步到order表
                             * 当前系统暂时未设置子订单的情况
                             * 所以直接同步主订单信息，后期需要优化 添加子订单 管理
                             * */
                            alibabaService.getLogisticsInfos(orderId);

                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.comfirm_receivegoods)){
                            logger.info("订单确认收货消息订阅");
                           // jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                          //  String  orderId =  jsonObject.get("orderId").toString();
                           // logger.info(orderId);

                            //alibabaService.getLogisticsInfos(orderId);

                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.order_success)){
                            logger.info("订单交易成功消息 订阅");


                        }
                        else if(jsonObject.get("type").toString().equals(GlobalConfig.ORDER_BUYER_CLOSE)){
                            logger.info("买家关闭订单 订阅");


                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.REFUND_IN_SALES)){
                            logger.info("订单售中退款 订阅");//


                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.ORDER_REFUND_AFTER_SALES)){
                            logger.info("订单售后退款  订阅");


                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.PRODUCT_DELETE)){
                            logger.info("产品删除 订阅");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  productId =  jsonObject.get("productIds").toString();
                            adminGoodsService.delete4Message(productId);


                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.PRODUCT_EXPIRE)){
                            logger.info("产品下架productIds 订阅");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  productId =  jsonObject.get("productIds").toString();
                            adminGoodsService.delete4Message(productId);


                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.PRODUCT_AUDIT)){
                            logger.info("产品审核下架productIds 订阅");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  productId =  jsonObject.get("productIds").toString();
                            adminGoodsService.delete4Message(productId);

                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.SUPER_BUY_PRICE)){
                            logger.info("超买价变更消息订阅");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  productId =  jsonObject.get("productIds").toString();
                            String  status =  jsonObject.get("status").toString();//DELETE商品不再商品池,UPDATE 超买价更新
                            if(status.equals("DELETE")){
                                logger.info("商品已不再商品池,数据库逻辑删除");
                                adminGoodsService.delete4Message(productId);
                            }else if(status.equals("UPDATE")){
                                logger.info("超买价变更，此处应该更新成本价");
                            }
                        }else if(jsonObject.get("type").toString().equals(GlobalConfig.BUYER_PAYED_SUCCEED)){
                            logger.info("采购付款成功消息订阅");
                            jsonObject = JSONObject.parseObject(jsonObject.get("data").toString());
                            String  orderId =  jsonObject.get("orderId").toString();
                            //adminGoodsService.delete4Message(productId);
                            logger.info("更新采购状态未已经支付");
                            adminOrderService.updatePuchasingStatus(orderId);



                        }

                        //logger.info("转换");
                    } catch (Exception e) {
                        success = false;
                    }
                }
                return success;
            }
        };
        client.setTunaMessageHandler(tunaMessageHandler);

        /**
         * 3. 启动 Client
         */
        client.connect();

        /**
         * 4. 在应用关闭时，关闭客户端
         */
        // client.shutdown();
    }



}
